#!/bin/bash

# ============================================
# Vue3 + Vite 前端项目快速部署脚本
# ============================================

set -e  # 遇到错误立即退出

# 颜色输出
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# 配置变量（请根据实际情况修改）
SERVER_USER="root"
SERVER_IP="10.170.129.4"
SERVER_PATH="/var/www/frontend"
NGINX_CONF_PATH="./deploy/nginx/frontend.conf"
NGINX_SERVER_CONF_PATH="/etc/nginx/conf.d/frontend.conf"

# 提示信息函数
echo_info() {
    echo -e "${GREEN}[INFO]${NC} $1"
}

echo_warn() {
    echo -e "${YELLOW}[WARN]${NC} $1"
}

echo_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

echo_step() {
    echo -e "${BLUE}[STEP]${NC} $1"
}

# 检查命令是否存在
check_command() {
    if ! command -v $1 &> /dev/null; then
        echo_error "$1 未安装，请先安装"
        exit 1
    fi
}

# 检查是否在项目根目录
if [ ! -d "web" ]; then
    echo_error "请在项目根目录执行此脚本"
    exit 1
fi

echo_info "============================================"
echo_info "Vue3 + Vite 前端项目部署脚本"
echo_info "============================================"
echo ""

# ============================================
# 步骤1：检查环境
# ============================================
echo_step "步骤1: 检查环境..."
check_command "npm"
check_command "rsync"
echo_info "✓ 环境检查通过"
echo ""

# ============================================
# 步骤2：配置环境变量
# ============================================
echo_step "步骤2: 配置环境变量..."
cd web

if [ ! -f ".env.production" ]; then
    echo_warn ".env.production 文件不存在，正在创建..."
    cat > .env.production << EOF
# API 地址（生产环境）
# 注意：前端代码中 API 路径已经包含 /api/，所以这里不要包含 /api/
VITE_API_URL=http://${SERVER_IP}:8000/

# 公共路径
VITE_PUBLIC_PATH=/

# 开发服务器端口
VITE_PORT=3000

# 构建输出目录
VITE_DIST_PATH=dist
EOF
    echo_warn "已创建 .env.production 文件，请确认配置是否正确"
    echo_warn "当前配置：VITE_API_URL=http://${SERVER_IP}:8000/"
    read -p "按 Enter 继续，或 Ctrl+C 退出修改配置..."
else
    echo_info "✓ .env.production 文件已存在"
    echo_info "当前配置："
    grep "VITE_API_URL" .env.production || echo_warn "未找到 VITE_API_URL 配置"
fi
echo ""

# ============================================
# 步骤3：安装依赖
# ============================================
echo_step "步骤3: 安装依赖..."
if [ ! -d "node_modules" ]; then
    echo_info "正在安装依赖..."
    npm install
else
    echo_info "依赖已存在，跳过安装"
    read -p "是否重新安装依赖？(y/N): " reinstall
    if [[ $reinstall =~ ^[Yy]$ ]]; then
        npm install
    fi
fi
echo_info "✓ 依赖安装完成"
echo ""

# ============================================
# 步骤4：构建项目
# ============================================
echo_step "步骤4: 构建项目..."
echo_info "开始构建生产版本..."
npm run build

if [ $? -ne 0 ]; then
    echo_error "构建失败！"
    exit 1
fi

if [ ! -d "dist" ]; then
    echo_error "构建目录 dist 不存在！"
    exit 1
fi

echo_info "✓ 构建完成！"
echo ""

# ============================================
# 步骤5：上传文件
# ============================================
echo_step "步骤5: 上传文件到服务器..."
cd ..

echo_info "服务器信息："
echo_info "  地址: ${SERVER_USER}@${SERVER_IP}"
echo_info "  路径: ${SERVER_PATH}"
echo ""

read -p "是否上传文件到服务器？(Y/n): " upload
if [[ ! $upload =~ ^[Nn]$ ]]; then
    echo_info "创建服务器目录..."
    ssh ${SERVER_USER}@${SERVER_IP} "mkdir -p ${SERVER_PATH}"
    
    echo_info "上传文件（排除 .map 文件）..."
    rsync -avz --delete --progress \
        --exclude '*.map' \
        web/dist/ ${SERVER_USER}@${SERVER_IP}:${SERVER_PATH}/
    
    if [ $? -ne 0 ]; then
        echo_error "文件上传失败！"
        exit 1
    fi
    
    echo_info "✓ 文件上传完成！"
    
    # 设置文件权限
    echo_info "设置文件权限..."
    ssh ${SERVER_USER}@${SERVER_IP} "chown -R root:root ${SERVER_PATH} && chmod -R 755 ${SERVER_PATH}"
    echo_info "✓ 权限设置完成"
else
    echo_warn "跳过文件上传"
fi
echo ""

# ============================================
# 步骤6：配置 Nginx
# ============================================
echo_step "步骤6: 配置 Nginx..."
read -p "是否配置 Nginx？(Y/n): " config_nginx
if [[ ! $config_nginx =~ ^[Nn]$ ]]; then
    echo_info "上传 Nginx 配置文件..."
    scp ${NGINX_CONF_PATH} ${SERVER_USER}@${SERVER_IP}:${NGINX_SERVER_CONF_PATH}
    
    if [ $? -ne 0 ]; then
        echo_warn "配置文件上传失败，请手动上传"
        echo_warn "命令: scp ${NGINX_CONF_PATH} ${SERVER_USER}@${SERVER_IP}:${NGINX_SERVER_CONF_PATH}"
    else
        echo_info "✓ 配置文件上传完成"
        
        echo_info "测试 Nginx 配置..."
        ssh ${SERVER_USER}@${SERVER_IP} "sudo nginx -t"
        
        if [ $? -eq 0 ]; then
            read -p "配置测试通过，是否重新加载 Nginx？(Y/n): " reload
            if [[ ! $reload =~ ^[Nn]$ ]]; then
                ssh ${SERVER_USER}@${SERVER_IP} "sudo systemctl reload nginx"
                echo_info "✓ Nginx 配置已重新加载"
            fi
        else
            echo_error "Nginx 配置测试失败，请检查配置文件"
        fi
    fi
else
    echo_warn "跳过 Nginx 配置"
fi
echo ""

# ============================================
# 步骤7：完成
# ============================================
echo_info "============================================"
echo_info "部署完成！"
echo_info "============================================"
echo_info "前端地址: http://${SERVER_IP}"
echo_info "服务器路径: ${SERVER_PATH}"
echo_info "============================================"
echo ""
echo_info "下一步操作："
echo_info "1. 在浏览器访问: http://${SERVER_IP}"
echo_info "2. 检查功能是否正常"
echo_info "3. 查看日志（如有问题）:"
echo_info "   ssh ${SERVER_USER}@${SERVER_IP}"
echo_info "   sudo tail -f /var/log/nginx/frontend_error.log"
echo ""

